package com.wl.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.kernel.util.ResponseChecker;
import com.alipay.easysdk.payment.facetoface.models.AlipayTradePrecreateResponse;
import com.mysql.cj.util.StringUtils;
import com.wl.mapper.OrdersMapper;
import com.wl.pojo.Orders;
import com.wl.pojo.model.UserToken;
import com.wl.service.OrderService;
import com.wl.util.MyUtil;
import com.wl.util.MybatisUtils;
import com.wl.util.RedisUtil;
import com.wl.util.TokenUtils;
import lombok.SneakyThrows;
import redis.clients.jedis.Jedis;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: treeHole
 * @author: 吴磊
 * @create: 2021-07-07 10:19
 */
public class OrderServiceImpl implements OrderService {

    private OrdersMapper ordersMapper = MybatisUtils.getMapper(OrdersMapper.class);

    @Override
    public Boolean deleteOrder(HttpServletRequest request) {
        String orderId = request.getParameter("orderId");
        Integer integer = ordersMapper.deleteOrderById(orderId);
        if (integer <= 0) {
            return false;
        }
        return true;
    }


    @Override
    public Map<String, Object> getAllOrder(HttpServletRequest request) {
        Map<String, Object> resmap = new HashMap<>();
        String page = request.getParameter("curPage");
        int curPage = 1;
        if (page != null && Integer.parseInt(page) > 0) {
            curPage = Integer.parseInt(page);
        }
        int start = (curPage - 1) * 10;
        int total = ordersMapper.getAllOrderCount();
        List<Orders> allOrderList = ordersMapper.getAllOrder(start);
        resmap.put("total", total);
        resmap.put("orders", allOrderList);
        return resmap;
    }


    @SneakyThrows
    @Override
    public Map<String, Object> FaceTofACEPay(HttpServletRequest request, Orders orders) {
        //获取二维码的同时要生成订单号
        String orderId = MyUtil.getUUID();
        orders.setOrderId(orderId);
        //获取当前日期
        String orderDate = MyUtil.getCurrentDetailedTime();
        orders.setOrderDate(orderDate);

        String token = TokenUtils.parseTokenToken(request);
        if (StringUtils.isNullOrEmpty(token)) {
            //用户没有登录，匿名赞赏
            orders.setOrderBuyerId("");
            orders.setOrderBuyerName("匿名");
        } else {
            //用户已经登录
            UserToken loginUser = TokenUtils.parseTokenToUserToken(token);
            orders.setOrderBuyerId(loginUser.getUserId());
            orders.setOrderBuyerName(loginUser.getUserName());
        }

        HashMap<String, Object> map = new HashMap<>();
        AlipayTradePrecreateResponse response = Factory.Payment.FaceToFace().preCreate("树洞赞赏", orderId, "" + orders.getOrderAmount());
        if (ResponseChecker.success(response)) {
            String qrCode = response.getQrCode();
            map.put("qrCode", qrCode);
            map.put("orderId", orderId);
            Jedis jedis = RedisUtil.getJedis();
            jedis.setex(orderId, 60L * 15, JSON.toJSONString(orders));
            jedis.close();
        } else {
            map.put("qrCode", "");
            map.put("orderId", "");
        }
        return map;
    }

    @SneakyThrows
    @Override
    public String notifyUrl(HttpServletRequest request) {
        Map<String, String> map = new HashMap();
        Enumeration<String> parameterNames = request.getParameterNames();
        while (parameterNames.hasMoreElements()) {
            String key = parameterNames.nextElement();
            String value = request.getParameter(key);
            map.put(key, value);
        }
        //验签
        try {
//            if (Factory.Payment.Common().verifyNotify(map)) {
            //验证用户的支付结果
            String trade_status = request.getParameter("trade_status");
            if ("TRADE_SUCCESS".equals(trade_status)) {
                //这里可以更新订单的状态等等。。
                Jedis jedis = RedisUtil.getJedis();
                String orderId = map.get("out_trade_no");
                String jsonOrder = jedis.get(orderId);
                Orders orders = JSON.toJavaObject(JSONObject.parseObject(jsonOrder), Orders.class);
                OrdersMapper ordersMapper = MybatisUtils.getMapper(OrdersMapper.class);
                ordersMapper.insertOrder(orders);
                jedis.del(orderId);
                jedis.close();
            }
//            } else {
//                return "fail";
//            }
        } catch (Exception e) {
            return "fail";
        }
        return "success";
    }


}
